/**配置OAuth2验证服务器（Authentication Server）：实现Token的生成、刷新、验证，验证成功后的Token会转换成用户及其权限信息
 * 1.核心依赖：spring-cloud-starter-oauth2（含spring-cloud-starter-security和spring-security-jwt）
 * 2.可选：启动类上加注解@EnableResourceServer，此时要在ebSecurityConfig配置文件中放行/oauth/**
 * 3.建立@Configuration和@EnableAuthorizationServer注解的Oauth Server配置文件，继承AuthorizationServerConfigurerAdapter，覆写其中至少三个方法
 *   1）ClientDetailsServiceConfigurer：configure(ClientDetailsServiceConfigurer clients) 客户端配置，配置接入客户端的授权类型、授权范围、秘钥等内容
 *   2）AuthorizationServerSecurityConfigurer：configure(AuthorizationServerSecurityConfigurer security) token端点安全配置，用来配置访问策略、认证策略、加密方式；
 *   3）AuthorizationServerEndpointsConfigurer：configure(AuthorizationServerEndpointsConfigurer endpoints) 端点配置，主要配置授权服务器的token存储方式、token转换、端点增强、端点自定义、token授权、token生成等
 * 4.建立@Configuration和@EnableWebSecurity注解的Spring Security配置文件，继承WebSecurityConfigurerAdapter，注入三个Bean，可选覆写其中两个方法，
 *   1）注入Bean UserDetailsService，可以在其中配置用户名、密码、角色
 *   2）注入Bean AuthenticationManager 用来做验证
 *   3）注入Bean PasswordEncoder 用来做密码加解密，新版本必须
 *   4）覆写方法：configure(HttpSecurity http) httpSecurity中配置所有请求的安全验证（可选）
 *   5）覆写方法：configure(AuthenticationManagerBuilder auth)  配置用户名、密码、角色（可选）
 */
package com.example.demoauthserver;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
@RestController
@EnableResourceServer    //需对外暴露获取token的API和验证token的API，所以该程序也是一个资源服务器
@EnableEurekaClient
public class DemoAuthServerApplication {

    //必配端点：通过令牌获取用户信息（/user）
//     @RequestMapping(value = "/user", produces = "application/json")
//     public Map<String,Object> getUser(OAuth2Authentication user) {
//         Map<String,Object> userInfo=new HashMap<>();
//         userInfo.put("user",user.getUserAuthentication().getPrincipal());
//         userInfo.put("authorities", AuthorityUtils.authorityListToSet(user.getUserAuthentication().getAuthorities()));
//         System.out.println("111111111------"+userInfo);
//         return userInfo;
//     }
    /*等效替代*/
    @RequestMapping("/user")
    public Principal user(Principal user) {
        System.out.println("222222222-----"+user);
        return user;
    }

    @Autowired
    TokenStore myTokenStore;

    @RequestMapping(value = "/oauth/token/{clientid}", produces = "application/json")
    public Object getToken(@PathVariable  String clientid) {
        Collection<OAuth2AccessToken> tokens=myTokenStore.findTokensByClientId(clientid);
        return tokens;
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoAuthServerApplication.class, args);
    }

}
